// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/benchmark.h>
#include <melon/init/init.h>

#include <turbo/flags/flag.h>

#include <pollux/functions/registerer.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>
#include <pollux/vector/vector_fuzzer.h>

TURBO_FLAG(int64_t,fuzzer_seed, 99887766, "Seed for random input dataset generator");

using namespace kumo::pollux;
using namespace kumo::pollux::exec;
using namespace kumo::pollux::functions;
using namespace kumo::pollux::test;

namespace {

class FeatureNormailzationBenchmark
    : public functions::test::FunctionBenchmarkBase {
 public:
  explicit FeatureNormailzationBenchmark() : FunctionBenchmarkBase() {
    prestosql::registerComparisonFunctions();
    prestosql::registerArithmeticFunctions();

    // Set input schema.
    inputType_ = ROW({
        {"a", REAL()},
    });

    // Generate input data.
    rowVector_ = make_row_vector(100);
  }

  RowVectorPtr make_row_vector(vector_size_t size) {
    VectorFuzzer::Options opts;
    opts.vectorSize = size;
    opts.nullRatio = 0;
    VectorFuzzer fuzzer(opts, pool(), FLAGS_fuzzer_seed);

    std::vector<VectorPtr> children{fuzzer.fuzzFlat(REAL())};
    float* rawValues =
        children.at(0)->as<FlatVector<float>>()->mutableRawValues();
    for (int i = 0; i < size; i++) {
      // fuzzFlat returns values in the range [0, 1), transform it into the
      // range [0, 2).
      rawValues[i] = rawValues[i] * 2;
    }
    // Hard code a couple values to ensure the range of data is never entirely
    // in the ranges [0, 1) or [1, 2).
    rawValues[0] = 0;
    rawValues[size - 1] = 1;

    return std::make_shared<RowVector>(
        pool(), inputType_, nullptr, size, std::move(children));
  }

  // Runs `expression` `times` thousand times.
  size_t run(const std::string& expression, size_t times = 1'000) {
    melon::BenchmarkSuspender suspender;
    auto exprSet = compileExpression(expression, inputType_);
    suspender.dismiss();

    size_t count = 0;
    for (auto i = 0; i < times; i++) {
      auto result = evaluate(exprSet, rowVector_);
      count += result->size();
    }
    return count;
  }

 private:
  TypePtr inputType_;
  RowVectorPtr rowVector_;
};

std::unique_ptr<FeatureNormailzationBenchmark> benchmark;

// Benchmark a common calculation used in machine learning to normalize floating
// point features.
BENCHMARK(normalize) {
  // floor(a) = 1 will return both true and false on some of the rows.
  benchmark->run(
      "clamp(0.05::REAL * (20.5::REAL + if(floor(a) = 1::REAL, 1.0::REAL, 0.0::REAL)), (-10.0)::REAL, 10.0::REAL)");
}

BENCHMARK(normalizeConstant) {
  // floor(a) = 2 will always return false.
  benchmark->run(
      "clamp(0.05::REAL * (20.5::REAL + if(floor(a) = 2::REAL, 1.0::REAL, 0.0::REAL)), (-10.0)::REAL, 10.0::REAL)");
}

} // namespace

int main(int argc, char* argv[]) {
  melon::Init init{&argc, &argv};
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  memory::MemoryManager::initialize({});
  benchmark = std::make_unique<FeatureNormailzationBenchmark>();
  melon::runBenchmarks();
  benchmark.reset();
  return 0;
}
